﻿using Service.Domain.Entities;
using Service.Domain.Entities.User;
using Service.Domain.Interfaces;
using Service.Domain.Interfaces.DomainService;
using Service.Domain.Interfaces.Factories;
using Service.Domain.Interfaces.Repositories;
using Service.Infrastructure;
using Service.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service.Domain.Services
{
    public class UserService : IUserService
    {
        readonly IUserRepository userRepository;
        readonly IPermissionRepository permissionRepository;
        readonly IUserFactory userFactory;

        public UserService(IUserRepository userRepository, IPermissionRepository permissionRepository, IUserFactory userFactory)
        {
            this.userRepository = userRepository;
            this.permissionRepository = permissionRepository;
            this.userFactory = userFactory;
        }

        public async Task<UserInfo> Login(string userName, string password)
        {
            if (string.IsNullOrWhiteSpace(userName)) throw new BaseException(ExceptionType.UserNameRequired.ToString(), "The username is required");
            if (string.IsNullOrWhiteSpace(password)) throw new BaseException(ExceptionType.PasswordRequired.ToString(), "The password is required");

            var model = await userRepository.FindByUserNameOrMobileOrEmail(userName, password);

            if (model == null) throw new BaseException(ExceptionType.UserNameOrPasswordInvalid.ToString(), "Username or password is invalid");

            var domain = this.userFactory.CreateRoot(model);

            await domain.GetRoles();
            //// 1.读取权限
            //var permissions = await this.permissionRepository.GetUserPermissions(model.Id);

            //// 2.组装成树结构
            //permissions = this.CombinePermissionTrees(permissions);

            return (model);
        }
    }
}
